//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using OpenLS.Chart;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet.Chart
{
    class RangeMultiLevelStringReference: MultiLevelStringReference
    {
        protected override void ReadXmlCore(ReadContext context)
        {
            using (ReadContext c = context.Read("multiLvlStrRef"))
            {
                string formula = c.ReadElementString("f");
                Workbook workbook = context.GetData<Workbook>();
                Worksheet worksheet = context.GetData<Worksheet>();
                c.GetData<WorkbookResolver>().ResolveActions.Add //\\workbook.TempReader.ResolveActions.Add
    (
        delegate {if (worksheet != null)SetRange(new InvalidRange(worksheet, formula)); 
            else
            SetRange(new InvalidRange(workbook, formula)); });
                c.ReadOptionalElementAs<MultiLevelStringData>("multiLvlStrCache");
                Extension = c.ReadOptionalElement<ExtensionElement>("extLst");

            }

        }

        public override string Formula
        {
            get
            {
                return invalidRange.Formula; //\\ ToReference().FullLabel;
            }
        }

        internal void SetRange(InvalidRange range)
        {
            invalidRange = range;
            if (range.Range == null)
                return;
            range.Range.CellValueChanged += range_CellValueChanged;
            NotifyPropertyChanged("Values");

        }
        void range_CellValueChanged(object sender, EventArgs e)
        {
            NotifyPropertyChanged("Values");
            NotifyPropertyChanged("StringValues");
        }

        InvalidRange invalidRange;
        public override IEnumerable<object> Values
        {
            get {
                foreach (Cell cell in invalidRange.Range.GetNonEmptyCells())
                    yield return cell.Value; //\\sure?
            }
        }
	
    }
}
